<?php

namespace App\Http\Controllers\Admin;

use App\Enums\ProductStatus;
use App\Enums\RightsType;
use App\Exports\ProductExport;
use App\Http\Controllers\Controller;
use App\Jobs\DownloadsJob;
use App\Models\Download;
use App\Models\Product;
use App\Models\ProductToken;
use App\Services\ObsService;
use App\Services\ProductService;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;

class ProductController extends Controller
{
    /** @var ProductService */
    private $productService;

    /** @var ObsService */
    private $obsService;

    /**
     * ProductController constructor.
     */
    public function __construct(ProductService $productService, ObsService $obsService)
    {
        $this->productService = $productService;
        $this->obsService = $obsService;
    }

    /** 商品列表 */
    public function index()
    {
        $query = Product::query()
            ->with(['agent', 'store', 'resale_user.auth'])
            ->withCount(['available_tokens'])
            ->when(request()->agent_id, function ($q) {
                return $q->where('agent_id', request()->agent_id);
            })
            ->when(request()->keyword, function ($q) {
                return $q->where(function ($q2) {
                    $likeVal = '%' . request()->keyword . '%';
                    $q2->where('name', 'like', $likeVal)->orWhere('publisher_account', 'like', $likeVal);
                });
            })
            ->when(request()->start_date, function ($q) {
                $q->whereDate('created_at', '>=', request()->start_date);
            })
            ->when(request()->end_date, function ($q) {
                $q->whereDate('created_at', '<=', request()->end_date);
            })
            ->when(request()->type, function ($q) {
                return $q->where('type', request()->type);
            })
            ->orderByDesc('id');

        return paginate_result($query);
    }

    /** 查询商品详情 */
    public function show($id)
    {
        return Product::query()
            ->with(['resale_user', 'agent', 'store', 'category'])
            ->find($id);
    }

    /** 查询商品存证列表 */
    public function listProductTokens($id)
    {
        $query = ProductToken::query()
            ->where('product_id', $id)
            ->orderBy('id');

        return paginate_result($query);
    }

    /** 以树形结构返回所有分类数据 */
    public function getAgentCategories($agentId)
    {
        return $this->productService->getCategoryTree($agentId);
    }

    /** 商品发布 */
    public function releaseProduct($id)
    {
        request()->validate([
            'agent_id' => 'required',
            'name' => 'required',
            'category_id' => 'required',
            'display_price' => 'required',
            'buy_limit' => 'required',
            'rights_type' => 'enum_value:' . RightsType::class,
            'start_time' => 'nullable',
            'end_time' => 'nullable',
            'left_count' => 'required',
            'logo_url' => 'required',
            'asset_image_url' => 'nullable',
            'author' => 'nullable',
            'intro' => 'nullable',
            'description' => 'nullable',
            'test_only' => 'required | boolean',
        ]);

        $product = Product::query()->find($id);
        $maxInventory = $product->available_tokens()->count();
        if (request()->left_count > $maxInventory) {
            throw new AdminException('库存不能超过' . $maxInventory);
        }

        $product->agent_id = request()->agent_id;
        $product->name = request()->name;
        $product->category_id = request()->category_id;
        $product->test_only = request()->test_only;
        $product->price = toFen(request()->display_price);
        $product->buy_limit = request()->buy_limit;
        $product->rights_type = request()->rights_type;
        $product->start_time = request()->start_time;
        $product->end_time = request()->end_time;
        $product->left_count = request()->left_count;
        $product->logo_url = request()->logo_url;
        $product->asset_image_url = request()->asset_image_url;
        $product->author = request()->author;
        $product->intro = request()->intro ?: '';
        $product->description = request()->description ?: '';
        $product->status = ProductStatus::ON_SALE;
        $product->online_time = now();
        $product->save();
    }

    /** 商品下架 */
    public function offlineProduct($id)
    {
        $product = Product::query()->find($id);
        $product->status = ProductStatus::PAUSE;
        $product->save();
    }

    /** 上传商品图片 */
    public function uploadProductImage()
    {
        request()->validate([
            'file' => ['image', 'mimes:jpg,jpeg,png', 'max:2048'],
        ], [
            'file.max' => '图片尺寸不能超过2M',
            'file.mimes' => '图片格式必须为jpg/jpeg/png',
        ]);
        $key = 'product_image/' . uniqid();
        $file = request()->file('file');
        $imageUrl = $this->obsService->upload($key, $file);

        return [
            'image_url' => $imageUrl,
        ];
    }

    /**
     * 发行商品导出.
     */
    public function export()
    {
        $user = auth()->user();

        $file = '发行商品' . date('YmdHis') . uniqid() . '.xls';

        $download = Download::create([
            'agent_id' => 0,
            'user_id' => $user->id,
            'name' => $file,
            'url' => 'storage/' . $file,
            'status' => 0,
            'model' => ProductExport::class,
            'request' => json_encode(request()->all()),
        ]);

        dispatch(new DownloadsJob($download));
    }

    /*
     * 转售导出
     */
    public function resaleExport()
    {
        $user = auth()->user();

        $file = '转售商品' . date('YmdHis') . uniqid() . '.xls';

        $request = request()->all();
        $request->type = 'resale';

        $download = Download::create([
            'agent_id' => 0,
            'user_id' => $user->id,
            'name' => $file,
            'url' => 'storage/' . $file,
            'status' => 0,
            'model' => ProductExport::class,
            'request' => json_encode(request()->all()),
        ]);

        dispatch(new DownloadsJob($download));
    }

    /**
     * 盲盒导出.
     */
    public function blindExport()
    {
        $user = auth()->user();

        $file = '盲盒商品' . date('YmdHis') . uniqid() . '.xls';

        $request = request()->all();
        $request->type = 'blind';

        $download = Download::create([
            'agent_id' => 0,
            'user_id' => $user->id,
            'name' => $file,
            'url' => 'storage/' . $file,
            'status' => 0,
            'model' => ProductExport::class,
            'request' => json_encode(request()->all()),
        ]);

        dispatch(new DownloadsJob($download));
    }
}
